package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageUtils;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.StringInfoMatch;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.YearMonthDayPicker;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;


/**
 * 个人信息
 * 
 * @author Administrator
 * 
 */
@SuppressLint("InflateParams")
public class PersonalInformationActivity2 extends BaseActivity implements
    OnCheckedChangeListener {

  private final static int REQUEST_PARENT_IMAGE = 100;
  private final static int REQUEST_BABY_IMAGE = 101;

  private final static int REQUEST_BABY_BIRTHDAY = 104;

  private static final int REQUIRED_WIDTH = 300;
  private static final int REQUIRED_HEIGHT = 300;

  @InjectView(id = R.id.img_baby_avtar, click = true)
  private ImageView img_baby_avtar;
  @InjectView(id = R.id.img_parent_avatar, click = true)
  private ImageView img_parent_avtar;

  @InjectView(id = R.id.tv_label)
  private TextView tv_label;

  @InjectView(id = R.id.edit_baby_nickname, click = true)
  private EditText edit_baby_nickname;
  @InjectView(id = R.id.edit_parent_nickname, click = true)
  private EditText edit_parent_nickname;

  @InjectView(id = R.id.edittext_tall, click = true)
  private EditText edittext_tall;
  @InjectView(id = R.id.edittext_weight, click = true)
  private EditText edittext_weight;

  @InjectView(id = R.id.tv_baby_birth, click = false)
  private TextView tv_baby_birth;

  @InjectView(id = R.id.girllyt, click = true)
  private RelativeLayout girllyt;
  @InjectView(id = R.id.boylyt, click = true)
  private RelativeLayout boylyt;
  @InjectView(id = R.id.radio1, click = true)
  private RadioButton radioButton1;
  @InjectView(id = R.id.radio2, click = true)
  private RadioButton radioButton2;
  @InjectView(id = R.id.appellations_tv, click = true)
  private TextView appellations_tv;

  private List<String> list = new ArrayList<String>();
  private AlertDialog.Builder builder;
  private AlertDialog alertDialog;

  @InjectView(id = R.id.tv_ch, click = true)
  private TextView tv_ch;

  // 家长称谓
  private String mApellationName = "爸爸";

  private LeUser mLeUser, mLeUserGetted;
  private LeMachine mLeBaby;
  private Uri BabyUri;
  private Uri ParentUri;
  private String[] mArrName; // 称呼

  private int mGender = 1;

  private String parentAvatar, babyAvatar;

  /**
   * 称呼
   */
  public void ShowDialog() {
    Context context = this;
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.formcommonlist, null);
    ListView myListView = (ListView) layout
        .findViewById(R.id.formcustomspinner_list);
    MyAdapter adapter = new MyAdapter(context, list);
    myListView.setAdapter(adapter);
    myListView.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int positon,
          long id) {
        mApellationName = list.get(positon).toString();
        tv_ch.setText(mApellationName);

        if (Tools.isNullStr(ParentUri)) {
          if (mApellationName.contains("爸爸") || mApellationName.contains("爷爷")
              || mApellationName.contains("外公")) {
            img_parent_avtar
                .setImageResource(R.drawable.defaut_parent_avtar_male);
          } else {
            img_parent_avtar
                .setImageResource(R.drawable.defaut_parent_avtar_female);
          }
        }

        if (alertDialog != null) {
          alertDialog.dismiss();
        }
      }
    });
    builder = new AlertDialog.Builder(context);
    builder.setView(layout);
    alertDialog = builder.create();
    alertDialog.show();
  }

  class MyAdapter extends BaseAdapter {
    private List<String> mlist;
    private Context mContext;

    public MyAdapter(Context context, List<String> list) {
      this.mContext = context;
      mlist = new ArrayList<String>();
      this.mlist = list;
    }

    @Override
    public int getCount() {
      return mlist.size();
    }

    @Override
    public Object getItem(int position) {
      return mlist.get(position);
    }

    @Override
    public long getItemId(int position) {
      return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      Person person = null;
      if (convertView == null) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(R.layout.rtu_item, null);
        person = new Person();
        person.name = (TextView) convertView.findViewById(R.id.tv_name);
        convertView.setTag(person);
      } else {
        person = (Person) convertView.getTag();
      }
      person.name.setText(list.get(position).toString());
      return convertView;
    }

    class Person {
      TextView name;
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.personal_information_layout2);
    setTitle("个人信息");
    initView();
  }

  private void getParentInfo() {
    if (mLeUser != null) {
      new CustomAsyncTask(this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
            mLeUserGetted = JsonSerializer.getInstance().deserialize(
                result.data, LeUser.class);

            if (mLeUserGetted != null) {
              edit_parent_nickname.setText(mLeUserGetted.nickname);
              mApellationName = mLeUserGetted.callname;

              if (Tools.isNotEmpty(mApellationName)
                  && Tools.isNullStr(ParentUri)) {
                if (mApellationName.contains("爸爸")
                    || mApellationName.contains("爷爷")
                    || mApellationName.contains("外公")) {
                  img_parent_avtar
                      .setImageResource(R.drawable.defaut_parent_avtar_male);
                } else {
                  img_parent_avtar
                      .setImageResource(R.drawable.defaut_parent_avtar_female);
                }
              }
            }
          }

          dismissLoading();

          if (Tools.isEmpty(edit_baby_nickname.getText().toString())
              || Tools.isEmpty(tv_baby_birth.getText().toString())
              || Tools.isEmpty(edit_parent_nickname.getText().toString())
              || Tools.isEmpty(tv_ch.getText().toString())) {
            // tv_label.setVisibility(View.VISIBLE);
          } else {
            // tv_label.setVisibility(View.GONE);
          }

        }

        @Override
        public ResponseResult doInbackground(Activity activity) {
          HashMap<String, Object> param_ = new HashMap<String, Object>();
          param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
          return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/member/"
              + mLeUser.sno, param_, HttpUtils.TAG_GET_REQUEST);
        }
      }).execute("请检查网络连接!");
    }

  }

  private void getBabyInfo() {
    showloading("");
    if (mLeUser != null && mLeUser.machine != null
        && Tools.isNotEmpty(mLeUser.machine.id)) {
      new CustomAsyncTask(this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
            mLeBaby = JsonSerializer.getInstance().deserialize(result.data,
                LeMachine.class);
          } else if (Tools.isNotEmpty(mLeUser.machine)) {
            mLeBaby = mLeUser.machine;
          }

          if (Tools.isNotEmpty(mLeBaby)) {
            edit_baby_nickname.setText(mLeBaby.name);
            tv_baby_birth.setText(mLeBaby.dob);

            if (Tools.isNotNullStr(mLeBaby.height))
              edittext_tall.setText(mLeBaby.height);
            if (Tools.isNotNullStr(mLeBaby.weight))
              edittext_weight.setText(mLeBaby.weight);

            if (mLeBaby.gender == 0) {
              mGender = 0;
              radioButton1.setChecked(true);
              radioButton2.setChecked(false);

              if (Tools.isNullStr(BabyUri)) {
                img_baby_avtar
                    .setImageResource(R.drawable.defaut_baby_avtar_female);
              }
            } else {
              mGender = 1;
              radioButton2.setChecked(true);
              radioButton1.setChecked(false);

              if (Tools.isNullStr(BabyUri)) {
                img_baby_avtar
                    .setImageResource(R.drawable.defaut_baby_avtar_male);
              }
            }
          }

          getParentInfo();
        }

        @Override
        public ResponseResult doInbackground(Activity activity) {

          HashMap<String, Object> param_ = new HashMap<String, Object>();
          param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
          param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

          return HttpUtils.startRequest(HttpUtils.API_URL
              + "/api/2.0/member/machine/" + mLeUser.machine.id, param_,
              HttpUtils.TAG_GET_REQUEST);
        }
      }).execute("请检查网络连接!");
    }

  }

  @Override
  protected void onResume() {
    super.onResume();
  }

  private final StringInfoMatch stringMatch = new StringInfoMatch();

  private void initView() {
    mUprightButton.setText("完成");
    mUprightButton.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    mArrName = getResources().getStringArray(R.array.appellation_array_name);
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    mLeBaby = LeXiaoXiaoBanApp.getInstance().getBaby();

    // edit_baby_nickname.addTextChangedListener(new TextWatcher() {
    //
    // @Override
    // public void onTextChanged(CharSequence s, int start, int before, int
    // count) {
    // // TODO Auto-generated method stub
    //
    // }
    //
    // @Override
    // public void beforeTextChanged(CharSequence s, int start, int count,
    // int after) {
    // // TODO Auto-generated method stub
    //
    // }
    //
    // @Override
    // public void afterTextChanged(Editable s) {
    // if (s != null && s.length() == 0) {
    // tv_label.setVisibility(View.VISIBLE);
    // }
    // }
    // });
    //
    // edit_parent_nickname.addTextChangedListener(new TextWatcher() {
    //
    // @Override
    // public void onTextChanged(CharSequence s, int start, int before, int
    // count) {
    // // TODO Auto-generated method stub
    //
    // }
    //
    // @Override
    // public void beforeTextChanged(CharSequence s, int start, int count,
    // int after) {
    // // TODO Auto-generated method stub
    //
    // }
    //
    // @Override
    // public void afterTextChanged(Editable s) {
    // if (s != null && s.length() == 0) {
    // tv_label.setVisibility(View.VISIBLE);
    // }
    // }
    // });

    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);

    String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");
    if (Tools.isNotEmpty(babyImagePath)) {
      BabyUri = Uri.parse(babyImagePath);
      setImageViewContent(img_baby_avtar, BabyUri);
    } else {
      if (mLeBaby != null) {
        if (mLeBaby.gender == 0) {
          img_baby_avtar.setImageResource(R.drawable.defaut_baby_avtar_female);
        } else {
          img_baby_avtar.setImageResource(R.drawable.defaut_baby_avtar_male);
        }
      }
    }

    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
    if (Tools.isNotEmpty(parentImagePath)) {
      ParentUri = Uri.parse(parentImagePath);
      setImageViewContent(img_parent_avtar, ParentUri);
    } else {
      if (mLeUser != null && mLeUser.callname != null) {
        if (mLeUser.callname.contains("爸爸") || mLeUser.callname.contains("爷爷")
            || mLeUser.callname.contains("外公")) {
          img_parent_avtar
              .setImageResource(R.drawable.defaut_parent_avtar_male);
        } else {
          img_parent_avtar
              .setImageResource(R.drawable.defaut_parent_avtar_female);
        }
      }
    }

    list = Arrays.asList(mArrName);

    if (mLeUser != null) {
      if (Tools.isEmpty(mLeUser.nickname) || mLeUser.nickname.equals("null")) {
        edit_parent_nickname.setText("用户" + mLeUser.id);
      } else {
        edit_parent_nickname.setText(mLeUser.nickname);
      }

      // 称呼
      if (Tools.isNotEmpty(mArrName) && mArrName.length > 0) {
        for (int i = 0; i < mArrName.length; i++) {
          if (mArrName[i].contains(mLeUser.callname)) {
            tv_ch.setText(mArrName[i]);
            break;
          }
        }
      }
    }


//    Retrofit retrofit = new Retrofit.Builder()
//            .baseUrl("http://sapi.lexiaobao.net/")
//            //增加返回值为String的支持
//            .addConverterFactory(ScalarsConverterFactory.create())
//            //增加返回值为Gson的支持(以实体类返回)
//            .addConverterFactory(StringConverterFactory.create())
//            .addConverterFactory(GsonConverterFactory.create())
//            .build();
//
//
//    JdyService requestSerives = retrofit.create(JdyService.class);//这里采用的是Java的动态代理模式
//    Call<String> call = requestSerives.getBabyInfo(mLeUser.machine.id, mLeUser.sno, HttpUtils.KEY);
//   // 利用得到的Call对象，然后我们就发出网络请求了：
//    call.enqueue(new Callback<String>() {
//      @Override
//      public void onResponse(Call<String> call, Response<String> response) {
//int a = 0;
//      }
//
//      @Override
//      public void onFailure(Call<String> call, Throwable throwable) {
//        int a = 0;
//      }
//    });

    getBabyInfo();

    mUprightButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        v.startAnimation(mPressedAnimation);
        mPressedAnimation.setAnimationListener(new AnimationListener() {
          @Override
          public void onAnimationStart(Animation animation) {

          }

          @Override
          public void onAnimationRepeat(Animation animation) {

          }

          @Override
          public void onAnimationEnd(Animation animation) {

            if (Tools.isEmpty(edit_baby_nickname.getText().toString())
                || Tools.isEmpty(tv_baby_birth.getText().toString())
                || Tools.isEmpty(edit_parent_nickname.getText().toString())
                || Tools.isEmpty(tv_ch.getText().toString())) {
              // tv_label.setVisibility(View.VISIBLE);
              return;
            } else {
              // tv_label.setVisibility(View.GONE);
            }

            String height = edittext_tall.getText().toString().trim();
            String weight = edittext_weight.getText().toString().trim();
            if (Tools.isNotEmpty(height)
                && !stringMatch.ifMatchHeightFormat(height)) {
              toastShow("请输入正确身高!");
              return;
            }

            if (Tools.isNotEmpty(weight)
                && !stringMatch.ifMatchWeightFormat(weight)) {
              toastShow("请输入正确体重!");
              return;
            }

            if (radioButton1.isChecked()) {
              mGender = 0;
              mLeBaby.gender = 0;
            } else if (radioButton2.isChecked()) {
              mLeBaby.gender = 1;
              mGender = 1;
            }

            mLeBaby.dob = tv_baby_birth.getText().toString();
            mLeBaby.name = edit_baby_nickname.getText().toString();
            mLeBaby.height = edittext_tall.getText().toString();
            mLeBaby.weight = edittext_weight.getText().toString();

            LeXiaoXiaoBanApp.getInstance().setBaby(mLeBaby);

            Tools.saveLeBaby(mLeBaby);

            if (mLeUser != null && mLeUser.machine != null) {
              mLeUser.machine.name = mLeBaby.name;
              mLeUser.machine.dob = mLeBaby.dob;
              mLeUser.machine.gender = mLeBaby.gender;
            }

            String newParentName = edit_parent_nickname.getText().toString();
            if (Tools.isEmpty(newParentName) || "null".equals(newParentName)) {
              edit_parent_nickname.setText("用户" + mLeUser.id);
            } else {
              edit_parent_nickname.setText(newParentName);
            }

            if (mLeUser != null) {
              mLeUser.callname = tv_ch.getText().toString();
              mLeUser.nickname = newParentName;
            }
            LeXiaoXiaoBanApp.getInstance().setUser(mLeUser);
            Tools.saveLeUser(mLeUser);

            updateBabyInfo();
          }
        });
      }
    });

    img_baby_avtar.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(PersonalInformationActivity2.this,
            SelectPicPopupWindow.class);
        intent.putExtra("avatar_path",
            PathUtil.getBabyAvatarPath(getApplicationContext()));
        startActivityForResult(intent, REQUEST_BABY_IMAGE);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      }
    });

    tv_baby_birth.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            PersonalInformationActivity2.this).setMessageTitle("警告")
            .setMessage("修改宝宝的生日，之前的信息将会被删除，无法恢复，确定要修改吗？")
            .setNegativeButton("确定", new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                final YearMonthDayPicker ymdp = new YearMonthDayPicker(
                    PersonalInformationActivity2.this);
                ymdp.build(new OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    tv_baby_birth.setText(ymdp.getSelectedDate());
                  }
                }, null);
                ymdp.show();
                int dividerId = ymdp.getDialog().getContext().getResources()
                    .getIdentifier("android:id/titleDivider", null, null);
                View divider = ymdp.getDialog().findViewById(dividerId);
                divider.setBackgroundColor(PersonalInformationActivity2.this
                    .getResources().getColor(R.color.setting_top_background));
              }
            }).setPositiveButton("取消", new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

              }
            });
        if (!isFinishing()) {
          CustomCommonDialog dlg = cdb.create();
          dlg.show();
        }

      }
    });

    tv_ch.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        ShowDialog();
      }
    });

    img_parent_avtar.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(new Intent(
            PersonalInformationActivity2.this, SelectPicPopupWindow.class));
        intent.putExtra("avatar_path",
            PathUtil.getElderAvatarPath(getApplicationContext()));
        startActivityForResult(intent, REQUEST_PARENT_IMAGE);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      }
    });

    girllyt.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        if (!radioButton1.isChecked()) {
          radioButton1.setChecked(true);

          if (Tools.isNullStr(BabyUri)) {
            img_baby_avtar
                .setImageResource(R.drawable.defaut_baby_avtar_female);
          }
        }
      }
    });

    boylyt.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (!radioButton2.isChecked()) {
          radioButton2.setChecked(true);
          if (Tools.isNullStr(BabyUri)) {
            img_baby_avtar.setImageResource(R.drawable.defaut_baby_avtar_male);
          }
        }
      }
    });

    radioButton1.setOnCheckedChangeListener(this);
    radioButton2.setOnCheckedChangeListener(this);
  }

  @SuppressWarnings("unused")
  private void setBabyView() {
    if (mLeBaby != null) {
      edit_baby_nickname.setText(mLeBaby.name);
      if (mLeBaby.gender == 1) {
        // 王子
        radioButton1.setChecked(false);
        radioButton2.setChecked(true);
      } else if (mLeBaby.gender == 2) {
        // 公主
        radioButton1.setChecked(true);
        radioButton2.setChecked(false);
      }

      tv_baby_birth.setText(mLeBaby.dob);
    }
  }

  private void updateBabyInfo() {
    showloading("");

    if (Tools.isNotEmpty(edit_baby_nickname.getText().toString().trim())
        && Tools.isNotEmpty(tv_baby_birth.getText().toString().trim())
        || (radioButton1.isChecked() || radioButton2.isChecked())) {
      new CustomAsyncTask(this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          if (result.isSuccess()) {
            if (Tools.isNotNullStr(result.data)) {
              toastShow(result.data);
            }

            LeXiaoXiaoBanApp.getInstance().getBaby().dob = tv_baby_birth
                .getText().toString().trim();
          }

          updateParentInfo();
        }

        @Override
        public ResponseResult doInbackground(Activity activity) {

          HashMap<String, Object> param_ = new HashMap<String, Object>();
          param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
          param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
          param_.put("machine_id", mLeUser.machine.id);
          param_.put("name", edit_baby_nickname.getText().toString().trim());
          param_.put("avatar", babyAvatar);
          param_.put("gender", mGender);
          param_.put("dob", tv_baby_birth.getText().toString().trim());

          String height = edittext_tall.getText().toString().trim();
          String weight = edittext_weight.getText().toString().trim();

          if (Tools.isNotEmpty(height)) {
            param_.put("height", height);
          }

          if (Tools.isNotEmpty(weight)) {
            param_.put("weight", weight);
          }

          return HttpUtils.startRequest(HttpUtils.API_URL
              + "/api/2.0/member/machine/" + mLeUser.machine.id, param_,
              HttpUtils.TAG_PUT_REQUEST);
        }
      }).execute("请检查网络连接!");

    }
  }

  private void updateParentInfo() {
    if (Tools.isNotEmpty(edit_parent_nickname.getText().toString().trim())
        && Tools.isNotEmpty(mApellationName)) {

      new CustomAsyncTask(this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          if (result.isSuccess()) {
            toastShow(result.data);

            dismissLoading();

            Intent it = new Intent();
            it.setAction("updatepersonalinfo");
            sendBroadcast(it);

            finish();
          }
        }

        @Override
        public ResponseResult doInbackground(Activity activity) {
          HashMap<String, Object> param_ = new HashMap<String, Object>();
          param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
          param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
          param_.put("token", "test");
          param_.put("platform", "android");
          param_.put("avatar", parentAvatar);
          param_.put("nickname", edit_parent_nickname.getText().toString()
              .trim());
          param_.put("callname", mApellationName);

          return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/member/"
              + mLeUser.sno, param_, HttpUtils.TAG_PUT_REQUEST);
        }
      }).execute("请检查网络连接!");

    }
  }

  private void uploadBabyAvatar(final String filePath) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result != null) {
          babyAvatar = result.data;

          if (mLeBaby != null && Tools.isNotEmpty(babyAvatar)) {
            mLeBaby.avatar = HttpUtils.HOST_API + babyAvatar;
            LeXiaoXiaoBanApp.getInstance().setBaby(mLeBaby);
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_MOBILE_I, mLeUser.id);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_MODULE_I, "member/machine/avatar");

        return HttpUtils.startUploadRequest(HttpUtils.API_URL
            + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
            HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  private void uploadParentAvatar(final String filePath) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result != null) {
          parentAvatar = result.data;
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_MOBILE_I, mLeUser.id);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_MODULE_I, "member/avatar");

        return HttpUtils.startUploadRequest(HttpUtils.API_URL
            + HttpUtils.UPLOAD_AVATAR_METHOD_POST, param_, "Filedata",
            filePath, HttpUtils.TAG_POST_REQUEST);
      }
    }).execute("请检查网络连接!");
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent returnedIntent) {
    super.onActivityResult(requestCode, resultCode, returnedIntent);
    switch (requestCode) {
    case REQUEST_BABY_IMAGE:
      if (resultCode == RESULT_OK) {
        this.BabyUri = Uri.parse(returnedIntent.getExtras().getString("image"));
        setImageViewContent(img_baby_avtar, BabyUri);
        uploadBabyAvatar(this.BabyUri.getPath());
        storeUserInfo(Constant.BABY_AVATAR, BabyUri.toString());

        Intent it = new Intent();
        it.setAction("updatebabyheadimage");
        sendBroadcast(it);
      }
      break;
    case REQUEST_PARENT_IMAGE:
      if (resultCode == RESULT_OK) {
        this.ParentUri = Uri.parse(returnedIntent.getExtras()
            .getString("image"));
        setImageViewContent(img_parent_avtar, this.ParentUri);
        uploadParentAvatar(this.ParentUri.getPath());
        storeUserInfo(Constant.PARENT_AVATAR, this.ParentUri.toString());

        Intent it = new Intent();
        it.setAction("updateparentheadimage");
        sendBroadcast(it);
      }
      break;
    case REQUEST_BABY_BIRTHDAY:
      break;
    }
  }

  private void storeUserInfo(String key, String value) {
    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    prefs.edit().putString(key, value).apply();
  }

  private Bitmap setImageViewContent(ImageView source, Uri original) {
    if (original != Uri.EMPTY) {
      Bitmap originalBitmap = ImageUtils.getBitmapFromUri(this, original);
      if (originalBitmap != null) {
        Bitmap bm = ImageUtils.scaleCropToFit(originalBitmap, REQUIRED_WIDTH,
            REQUIRED_HEIGHT, true);
        source.setImageURI(null);
        if (bm != null) {
          source.setImageBitmap(bm);
        }
        return bm;
      }
    }
    return null;
  }

  @Override
  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    switch (buttonView.getId()) {
    case R.id.radio1:
      if (isChecked) {
        radioButton2.setChecked(false);
        if (Tools.isNullStr(BabyUri)) {
          img_baby_avtar.setImageResource(R.drawable.defaut_baby_avtar_female);
        }
      }
      break;
    case R.id.radio2:
      if (isChecked) {
        radioButton1.setChecked(false);
        if (Tools.isNullStr(BabyUri)) {
          img_baby_avtar.setImageResource(R.drawable.defaut_baby_avtar_male);
        }

      }

      break;
    default:
      break;
    }
  }

}
